package cn.tedu._05weibo0001.controller;


import cn.tedu._05weibo0001.mapper.UserMapper;
import cn.tedu._05weibo0001.pojo.dto.UserLoginDTO;
import cn.tedu._05weibo0001.pojo.dto.UserRegDTO;
import cn.tedu._05weibo0001.pojo.entity.User;
import cn.tedu._05weibo0001.pojo.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/v2/users/")
public class UserController {
   @Autowired(required = false)
    private UserMapper userMapper;

    /**
     * 1.注册功能
     */
    @RequestMapping("reg")
    public int regUser(@RequestBody UserRegDTO userRegDTO){
        String username = userRegDTO.getUsername();
        UserVo userVo = userMapper.selectUser(username);
        if (userVo==null){ //用户不存在
            User user = new User();
            BeanUtils.copyProperties(userRegDTO,user);
            int i = userMapper.insertUser(user);
            return 1;//注册成功
        }
        return 2;//注册失败

    }

    /**
     * 登录功能
     */
    @RequestMapping("login")
         /*
        1)接收数据
        2)判断是正确 return 1
        3) 如果密码错误return 2
           如果用户错误 return 3
         */
    public int login(@RequestBody UserLoginDTO userLoginDTO,HttpSession session){
        String username = userLoginDTO.getUsername();
        UserVo userVo = userMapper.selectUser(username);
        if (userVo==null){
            return 3;
        }
        if (userVo.getPassword().equals(userLoginDTO.getPassword())){
            session.setAttribute("user",userVo);
            return 1;
        }
        return 2;
    }






    /**
     * 获取当前用户功能
     */
    @RequestMapping("sessionUser")
    public UserVo sessionUser( HttpSession session){
        UserVo userVo = (UserVo) session.getAttribute("user");
        return userVo;
    }


    /**
     * 退出登录
     * (在服务器的内存中删除会话)
     *   1）登陆成功
     *   2）获取当前用户
     *   3）退出登录
     *   4）获取当前用户--无数据
     */
    @RequestMapping("logout")
    public void logOut(HttpSession session){
        session.removeAttribute("user");
    }


}

